package controller

import (
	"booksPro/dao"
	"booksPro/model"
	"net/http"
	"strconv"
	"text/template"
)

// 根据用户查询购物车以及购物项所有信息
func ToCarts(w http.ResponseWriter, r *http.Request) {
	session, flag := dao.IsLogin(r)
	if flag {
		//已登录,获取所有购物车信息
		cart, _ := dao.GetCartByUserID(session.UserID)
		if cart == nil {
			cart = &model.Cart{}
		}
		cart.UserName = session.Username
		cart.UserID = session.UserID
		session.Cart = cart
		t := template.Must(template.ParseFiles("views/pages/cart/cart.html"))
		t.Execute(w, session)

	} else {
		t := template.Must(template.ParseFiles("views/pages/user/login.html"))
		t.Execute(w, "请先登录!")
	}
}

func DeleteCart(w http.ResponseWriter, r *http.Request) {
	cartID := r.FormValue("cartID")
	dao.DeleteCartItemsByCartID(cartID)
	dao.DeleteCartByCartID(cartID)
	ToCarts(w, r)
}

func DeleteCartItem(w http.ResponseWriter, r *http.Request) {
	session, _ := dao.IsLogin(r)
	cartItemID := r.FormValue("cartItemID")
	icartItemID, _ := strconv.ParseInt(cartItemID, 10, 64)
	cart, _ := dao.GetCartByUserID(session.UserID)
	for k, v := range cart.CartItems {
		if v.CartItemID == icartItemID {
			cart.CartItems = append(cart.CartItems[:k], cart.CartItems[k+1:]...)
		}
	}
	dao.DeleteCartItemByCartItemID(cartItemID)
	dao.UpateCart(cart)
	ToCarts(w, r)
}

// 更新购物项
func UpdateCartItem(w http.ResponseWriter, r *http.Request) {
	cartItemID := r.FormValue("cartItemID")
	count := r.FormValue("count")
	icount, _ := strconv.ParseInt(count, 10, 64)
	//判断登录
	session, _ := dao.IsLogin(r)
	icartItemID, _ := strconv.ParseInt(cartItemID, 10, 64)
	cart, _ := dao.GetCartByUserID(session.UserID)
	for _, v := range cart.CartItems {
		if v.CartItemID == icartItemID {
			//更新对象
			v.Count = icount
			dao.UpdateCartItemCount(v)
		}
	}
	dao.UpateCart(cart)
	//不需要同步请求返回页面
	ToCarts(w, r)
	// //只需要异步请求，局部刷新
	// cart, _ = dao.GetCartByUserID(cart.UserID)
	// //将cart转为 json字符串
	// json, _ := json.Marshal(cart)
	// w.Write(json)
}
